<?php

namespace app\index\model;

use think\Db;
use think\Model;

class Diary extends Model
{
    public function index()
    {
        $res = Db::name('diary')
            ->field(['id', 'title', 'reading', 'reply', 'time', 'desc'])
            ->order('reading', 'desc')
            ->select();
        return $res;
    }

    public function readDiary($id)
    {
        $res = Db::view('user', 'nickname')
            ->view('diary', 'title,time,content,reading,reply', 'user.id = diary.uid')
            ->where('diary.id', 'eq', $id)
            ->find();

        $comment = Db::view('comment', 'time,content,uid')
                ->view('user', 'nickname', 'id = uid')
                ->where('did', 'eq', $id)
                ->select();

     if($res){
            $num = $res['reading'];
            $info = $num + 1;

             Db::name('diary')
                ->where('id',$id)
                ->update(['reading'=>$info]);
        }

        $res = [
            'arr1' => $res,
            'arr2' => $comment,
        ];
        return $res;
    }

    public function comment($arr)
    {
        $id = $arr['did'];
        $res = Db::name('comment')->insert($arr);

        if($res){
//            $arr = Db::name('diary')
//                ->field('reply')
//                ->where('id', $id)
//                ->find();
            $arr = Db::name('comment')
                ->where('did', $id)
                ->count('did');

            Db::name('diary')
                ->where('id', $id)
                ->update(['reply'=> $arr]);
        }

        return $res;
    }

    public function commitDiary($info)
    {
        $res = Db::name('diary')
            ->data($info)
            ->insert();
        return $res;
    }
}
